package service.impl;


import dao.SCMUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import pojo.Page;
import pojo.SCMUser;
import service.SCMUserService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Admin
 * @date 2022/11/8 17:54
 * @Description TODO
 * @Version 1.0
 **/
@Service
public class SCMUserServiceImpl implements SCMUserService {
    @Resource
    private SCMUserMapper scmUserMapper;

    @Override
    public SCMUser getUserByAccount(String account, String password) {
        return scmUserMapper.getUserByAccount(account,password);
    }

    @Override
    public int getCount(SCMUser scmUser) {
        return scmUserMapper.getCount(scmUser);
    }

    @Override
    public List<SCMUser> getUsers(Page<SCMUser> page, SCMUser scmUser) {
        return scmUserMapper.getUsers(page,scmUser);
    }

    @Override
    public SCMUser checkUser(String account) {
        return scmUserMapper.checkUser(account);
    }

    //注册
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void addUser(SCMUser u) {
        scmUserMapper.addUser(u);
        ArrayList<String> list = u.getModelName();
        for(String str:list){
            scmUserMapper.addModelName(u.getAccount(),str);
        }
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void addOrUpdateUser(SCMUser u) {
        //判断这个用户在数据库里面有没有
        SCMUser user = checkUser(u.getAccount());

        if(user != null){
            //删除原有的角色
            scmUserMapper.delModelName(u.getAccount());
            //修改scmuser
            scmUserMapper.updateUser(u);
        }else{
            scmUserMapper.addUser(u);
        }
        //如果角色名长度是4，说明四个角色都有，则这个用户就是管理员
        if(u.getModelName().size() == 4){
            scmUserMapper.addModelName(u.getAccount(),"admin");
        }else{
            for (int i=0;i<u.getModelName().size();i++){
                scmUserMapper.addModelName(u.getAccount(),u.getModelName().get(i));
            }
        }
    }


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void delUser(String account) {
        //删除原有的角色
        scmUserMapper.delModelName(account);
        //删除用户
        scmUserMapper.delUser(account);
    }

    @Override
    public SCMUser getUser(String account) {
        return scmUserMapper.getUser(account);
    }

}
